package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsBrandMapper;
import com.qf.mapper.DtsCategoryMapper;
import com.qf.mapper.DtsGoodsMapper;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsBrand;
import com.qf.pojo.DtsCategory;
import com.qf.pojo.DtsGoods;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsBrandService;
import com.qf.util.AliyunOSSUtil;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@Service
public class DtsBrandServiceImpl implements DtsBrandService {


    @Autowired
    DtsBrandMapper brandMapper;
    @Autowired
    DtsCategoryMapper categoryMapper;
    @Autowired
    DtsStorageMapper storageMapper;


    @Value("${aliyun.oss.endpoint}")
    String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    String bucketName;

    @Override
    public List<Integer> findBrandIds() {
        LambdaQueryWrapper<DtsBrand> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsBrand::getDeleted, false);

        List<DtsBrand> brands = brandMapper.selectList(wrapper);

        List<Integer> ids = brands.stream().map(dtsBrand -> {
            return dtsBrand.getId();
        }).collect(Collectors.toList());

        return ids;
    }

    @Override
    public List<Map<String, Object>> findBrandList() {
        LambdaQueryWrapper<DtsBrand> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsBrand::getDeleted, false);

        List<DtsBrand> brands = brandMapper.selectList(wrapper);

        List<Map<String,Object>> data = new ArrayList<>();

        for (DtsBrand brand : brands) {
            Map<String,Object> map = new HashMap<>();
            map.put("value", brand.getId() );
            map.put("label", brand.getName());

            data.add(map);
        }

        return data;
    }

    @Override
    public boolean isExists(Integer brandId) {
        LambdaQueryWrapper<DtsBrand> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsBrand::getDeleted, false);
        wrapper.eq(DtsBrand::getId, brandId);

        int count = brandMapper.selectCount(wrapper);
        return count != 0;
//        if(count == 0){
//            return false;
//        }
//        return true;
    }

    @Override
    public List<Integer> findBrandIdsByAdminId(Integer id) {
        LambdaQueryWrapper<DtsBrand> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsBrand::getDeleted, false);
        wrapper.eq(DtsBrand::getAdminId, id);

        List<DtsBrand> brands = brandMapper.selectList(wrapper);

        return  brands.stream().map(dtsBrand -> {
            return dtsBrand.getId();
        }).collect(Collectors.toList());
    }

    @Override
    public IPage<Map<String,Object>> findPage(Integer page, Integer limit, Integer id, String name, String sort, String order) {
        IPage<Map<String,Object>> ipage = new Page<>(page,limit);

        QueryWrapper<DtsBrand> wrapper = new QueryWrapper<>();

        if(!StringUtils.isEmpty(id)){
            wrapper.like("id",id);
        }

        if(!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        wrapper.eq("deleted ",false);
        if(order.equalsIgnoreCase("asc")){
            wrapper.orderByAsc(sort);
        }else{
            wrapper.orderByDesc(sort);
        }
        ipage =  brandMapper.selectMapsPage(ipage,wrapper);

        List<Map<String, Object>> records = ipage.getRecords();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Map<String, Object> record : records) {
            List<Integer> categoryIds = new ArrayList<>();
            Map<String, Object> item = new HashMap<>();
            QueryWrapper<DtsCategory> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id", (Integer) record.get("default_category_id"));
            DtsCategory category = categoryMapper.selectOne(wrapper1);
            if(category != null){
                Integer pid = category.getPid();
                Integer id1 = category.getId();
                categoryIds.add(pid);
                categoryIds.add(id1);
            }

            item.put("id", record.get("id"));
            item.put("name", record.get("name"));
            item.put("desc", record.get("desc"));
            item.put("picUrl", record.get("pic_url"));
            item.put("sortOrder", record.get("sort_order"));
            item.put("floorPrice", record.get("floor_price"));
            item.put("addTime", record.get("add_time"));
            item.put("updateTime", record.get("update_time"));
            item.put("shareUrl", record.get("share_url"));
            item.put("adminId", record.get("admin_id"));
            item.put("deleted", record.get("deleted"));
            item.put("commpany", record.get("commpany"));
            item.put("autoUpdateGood", record.get("auto_update_good"));
            item.put("shopUrl", record.get("shop_url"));
            item.put("defaultCategoryId", record.get("default_category_id"));
            item.put("defaultPages", record.get("default_pages"));
            item.put("addPrecent", record.get("add_precent"));
            item.put("categoryIds", categoryIds);
            mapList.add(item);
        }
        ipage.setRecords(mapList);

        return ipage;
    }

    @Override
    public Object insertBrand(DtsBrand brand) {
        LambdaQueryWrapper<DtsBrand> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsBrand::getName,brand.getName());
        DtsBrand brand1 = brandMapper.selectOne(wrapper);
        if(brand1!=null){
            return ResponseUtil.fail(-1,"品牌商名称已存在");
        }

        brand.setDeleted(false);
        brand.setAddTime(new Date());
        brand.setUpdateTime(new Date());


        brandMapper.insert(brand);
        return ResponseUtil.ok(brand);
    }

    @Autowired
    DtsGoodsMapper goodsMapper;
    @Override
    public Object deleteBrand(DtsBrand brand) {


        LambdaQueryWrapper<DtsGoods> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DtsGoods::getBrandId,brand.getId());
        DtsGoods goods = goodsMapper.selectOne(wrapper1);

        if(goods != null){
            return ResponseUtil.fail(-1,"该品牌商正在使用不能删除");
        }


        if(!StringUtils.isEmpty(brand.getPicUrl())) {
            deleteOss(brand);
        }
        brandMapper.deleteById(brand);
        return ResponseUtil.ok(brand);
    }

    private void deleteOss(DtsBrand brand) {
        DtsBrand dbbrand = brandMapper.selectById(brand.getId());
        String picUrl = dbbrand.getPicUrl();
        if(!StringUtils.isEmpty(picUrl)){
            LambdaQueryWrapper<DtsStorage> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DtsStorage::getUrl, picUrl);
            DtsStorage storage = storageMapper.selectOne(wrapper);
            AliyunOSSUtil.deleteFile(endpoint, accessKeyId, accessKeySecret, bucketName, storage.getName());
            storageMapper.deleteById(storage.getId());
        }
    }

    @Override
    public Object updateBrand(DtsBrand brand) {

        DtsBrand brand2 = brandMapper.selectById(brand);
        if(! brand.getName().equals(brand2.getName())){
            LambdaQueryWrapper<DtsBrand> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DtsBrand::getName,brand.getName());
            DtsBrand brand1 = brandMapper.selectOne(wrapper1);

            if(brand1!=null){
                return ResponseUtil.fail(-1,"品牌商名称已存在");
            }
        }

        DtsBrand brand1 = brandMapper.selectById(brand);
        Integer getUrlId = brand.getId();
        QueryWrapper<DtsBrand> getUrlWrapper = new QueryWrapper<>();
        getUrlWrapper.eq("id", getUrlId);
        LambdaQueryWrapper<DtsStorage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsStorage::getUrl,brand1.getPicUrl());
        DtsStorage storage = storageMapper.selectOne(wrapper);
        if(storage != null){
            if(storage.getUrl().equals(brand1.getPicUrl())){
                AliyunOSSUtil.deleteFile(endpoint,accessKeyId,accessKeySecret,bucketName,storage.getName());
                storageMapper.deleteById(storage);
            }
        }

        brand.setUpdateTime(new Date());
        brandMapper.updateById(brand);
        return ResponseUtil.ok(brand);
    }

}
